package CollectionTest.MyLink;
/*
单链表
 */
public class MyLink {
    Node head;
    int size;
    public MyLink(){
        head = null;
        size = 0;
    }

    //添加数据，插入尾节点
    public void myAdd(Object obj){
        //判断链表是否为空
        if(head == null){
            head = new Node(obj, null);
        }else{
            //如果不为空，查询尾节点
            Node lastNode = findNode(head);
            lastNode.next = new Node(obj,null);
        }
        size++;
    }

    //查询尾节点
    private Node findNode(Node node){
        if(node.next == null){
            return node;
        }
        return findNode(node.next);
    }

    //删除第p个节点链表元素
    public void myRemove(int p) {
        Node current = head;
        // 遍历链表直到p节点的前一节点
        if (p > 0 && p <= size) {
            if (p == 1) {// 若删除的是头节点
                head = current.next;
                size--;
                return;
            } else {
                for (int i = 1; i <= p; i++) {
                    if (i == p - 1) {
                        current.next = current.next.next;
                        size--;
                    } else {
                        current = current.next;
                    }
                }
            }
        }
    }

    public void print() {
        Node current = head;
        for (int i = 0; i < size; i++) {
            System.out.print(current.data + "-->");
            current = current.next;
        }
        System.out.println();
    }
}
